package cn.btks.databasehandler.handle.util;

import cn.btks.databasehandler.handle.pojo.BackUpConfig;
import org.quartz.*;

import javax.servlet.http.HttpServletRequest;
import java.sql.*;

/**
 * @Author lijun
 * @Date 2020/12/28 12:41
 */
public class QuartzUtil {

    /**
     * 创建定时任务 定时任务创建之后默认启动状态
     * @param scheduler   调度器
     * @param backUpConfig  定时任务信息类
     * @throws Exception
     */
    public static void createScheduleJob(Scheduler scheduler, BackUpConfig backUpConfig, String filePath){
        try {
            //获取到定时任务的执行类  必须是类的绝对路径名称
            //定时任务类需要是job类的具体实现 QuartzJobBean是job的抽象类。
            Class<? extends Job> jobClass = (Class<? extends Job>) Class.forName("cn.btks.databasehandler.handle.task.BackUpTask");
            // 构建定时任务信息
            JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(backUpConfig.getConfigName()).build();
            //将配置对象信息放入jobDataMap
            jobDetail.getJobDataMap().put("config",backUpConfig);
            jobDetail.getJobDataMap().put("filePath",filePath);
            // 设置定时任务执行方式
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(backUpConfig.getBackUpCron());
            // 构建触发器trigger
            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(backUpConfig.getConfigName()).withSchedule(scheduleBuilder).build();
            scheduler.scheduleJob(jobDetail, trigger);
        } catch (ClassNotFoundException e) {
            System.out.println("定时任务类路径出错：请输入类的绝对路径");
        } catch (SchedulerException e) {
            System.out.println("创建定时任务出错："+e.getMessage());
        }
    }

    /**
     * 根据任务名称暂停定时任务
     * @param scheduler  调度器
     * @param jobName    定时任务名称
     * @throws SchedulerException
     */
    public static void pauseScheduleJob(Scheduler scheduler, String jobName){
        JobKey jobKey = JobKey.jobKey(jobName);
        try {
            scheduler.pauseJob(jobKey);
        } catch (SchedulerException e) {
            System.out.println("暂停定时任务出错："+e.getMessage());
        }
    }

    /**
     * 根据任务名称恢复定时任务
     * @param scheduler  调度器
     * @param jobName    定时任务名称
     * @throws SchedulerException
     */
    public static void resumeScheduleJob(Scheduler scheduler, String jobName) {
        JobKey jobKey = JobKey.jobKey(jobName);
        try {
            scheduler.resumeJob(jobKey);
        } catch (SchedulerException e) {
            System.out.println("启动定时任务出错："+e.getMessage());
        }
    }

    /**
     * 根据任务名称立即运行一次定时任务
     * @param scheduler     调度器
     * @param jobName       定时任务名称
     * @throws SchedulerException
     */
    public static void runOnce(Scheduler scheduler, String jobName){
        JobKey jobKey = JobKey.jobKey(jobName);
        try {
            scheduler.triggerJob(jobKey);
        } catch (SchedulerException e) {
            System.out.println("运行定时任务出错："+e.getMessage());
        }
    }

    /**
     * 更新定时任务
     * @param scheduler   调度器
     * @param backUpConfig  定时任务信息类
     * @param filePath
     * @throws SchedulerException
     */
    public static void updateScheduleJob(Scheduler scheduler, BackUpConfig backUpConfig,String filePath)  {
        try {
            //获取到对应任务的触发器
            TriggerKey triggerKey = TriggerKey.triggerKey(backUpConfig.getConfigName());
            //设置定时任务执行方式
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(backUpConfig.getBackUpCron());
            JobKey jobKey = JobKey.jobKey(backUpConfig.getConfigName());
            JobDetail jobDetail = scheduler.getJobDetail(jobKey);
            JobDataMap jobDataMap = jobDetail.getJobDataMap();
            if(jobDataMap.get("config") != null){
                jobDataMap.put("config",backUpConfig);
            }
            if(jobDataMap.get("filePath") != null){
                jobDataMap.put("filePath",filePath);
            }
            //重新构建任务的触发器trigger
            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
            //重置对应的job
            scheduler.rescheduleJob(triggerKey, trigger);
        } catch (SchedulerException e) {
            System.out.println("更新定时任务出错："+e.getMessage());
        }
    }

    /**
     * 根据定时任务名称从调度器当中删除定时任务
     * @param scheduler 调度器
     * @param jobName   定时任务名称
     * @throws SchedulerException
     */
    public static void deleteScheduleJob(Scheduler scheduler, String jobName) {
        JobKey jobKey = JobKey.jobKey(jobName);
        try {
            scheduler.deleteJob(jobKey);
        } catch (SchedulerException e) {
            System.out.println("删除定时任务出错："+e.getMessage());
        }
    }

    /**
     * 获取数据库配置的根目录
     * @return
     * @throws SQLException
     */
    public static String getBaseDir(String url,String user,String password) throws SQLException {
        Connection connection = DriverManager.getConnection(url, user, password);//获取连接
        Statement statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery("select @@global.basedir");
        String rt = null;
        if (resultSet.next()) {
            rt = resultSet.getString(1);
        }
        resultSet.close();
        statement.close();
        connection.close();
        return rt;
    }
}
